package com.guigu.oss.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.guigu.oss.service.OssService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName:OssServiceImpl
 * @Description://TODO
 * @Author:taoLong
 * @Date:2021/12/6:10:05 星期一
 * @email:2391611102@qq.com or 2391611102qq@gmail.com
 */
@Service
public class OssServiceImpl implements OssService {

    /**
     * 地域节点
     */
    @Value("${aliyun.oss.file.endpoint}")
    private String endPoint;

    //id
    @Value("${aliyun.oss.file.keyid}")
    private String keyId;
    //秘钥
    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;
    //存储名称
    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file) {
        try {
            //重写文件名
            String fileName = UUID.randomUUID() + file.getOriginalFilename();

            //获取当前日期
            String currentDate = new DateTime().toString("yyyy/MM/dd");
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endPoint,keyId, keySecret);

            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream = file.getInputStream();
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。

            ossClient.putObject(bucketName,
                    currentDate + "/" + fileName.replaceAll("-", ""),
                    inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            //把上传之后的路径返回,拼接返回
            String url = "https://" + bucketName + "." + endPoint + "/" + currentDate + "/" + fileName.replaceAll("-", "");
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取临时访问OSS签名
     * 前端-用签名的方式上传文件
     * 官方链接地址：https://help.aliyun.com/document_detail/31926.html?spm=a2c4g.11186623.6.1737.5f3e3bd36kleqs
     *
     */
    @Override
    public Map<String, String> getSignature() {
        Map<String, String> respMap = new LinkedHashMap<>();
        //host的格式为 bucketName.endpoint
        String endpointForSig = "oss-cn-hangzhou.aliyuncs.com";
        String host = "https://" + bucketName + "." + endpointForSig;
        //callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        String callbackUrl = "";
        String dir = ""; // 用户上传文件时指定的前缀。
        OSSClient client = new OSSClient(endpointForSig, keyId, keySecret);
        try {
            //设置过期时间为半小时1800L
            long expireTime = 60 * 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            java.sql.Date expiration = new java.sql.Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConditions = new PolicyConditions();
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConditions);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            respMap.put("accessid", keyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

            JSONObject jasonCallback = new JSONObject();
            jasonCallback.put("callbackUrl", callbackUrl);
            jasonCallback.put("callbackBody",
                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            respMap.put("callback", base64CallbackBody);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return respMap;
    }

}
